package com.sdy.fs.biz.service.impl;

import com.sdy.common.constant.Constants;
import com.sdy.common.utils.OsPathUtil;
import com.sdy.common.utils.RandomUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.fs.biz.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

@Service("fsFileService")
@Slf4j
public class FileServiceImpl implements FileService {
    @Override
    public String saveFile(byte[] data, String filename, String type) {
        if (StringUtil.isBlank(type)) {
            type = "common";
        }
        String path = OsPathUtil.convertWithOs(Constants.UPLOAD_FILE_PATH + "/" + type);
        String fileName = System.currentTimeMillis() + "_" + RandomUtil.produceNumber(5) + filename.substring(filename.lastIndexOf('.'));
        File f = new File(path, fileName);
        File p = new File(path);
        if (!p.exists()) {
            p.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(f)) {
            fos.write(data);
        } catch (IOException e) {
            log.error("File save failed! ", e);
            return null;
        }
        return Constants.UPLOAD_FILE_PATH + "/" + type + "/" + fileName;
    }

    @Override
    public File getFileByDir(String filedir) {
        if (StringUtil.isBlank(filedir)) {
            return null;
        }
        if (filedir.contains("..")) {
            return null;
        }
        return new File(filedir);
    }

    @Override
    public File getFileById(String fileId) {
        return null;
    }

    public static void main(String[] args) {
        String w = new FileServiceImpl().saveFile(new byte[]{61,62,63,64}, "2333.4555", "111");
        System.out.println(w);
    }
}
